//
//  File.swift
//  
//
//  Created by WeCloudIOS on 2022/4/14.
//

import Foundation
import UIKit

//MARK: - 获取本地资源图片
class Tool{
    
    public static func SCImage(named name: String) -> UIImage? {
        UIImage(named: name, in: Bundle.module, compatibleWith: nil)
    }
    
}

//MARK: - 在线获取图片
extension UIImageView {
    func dowloadFromServer(url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFill) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
//                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data), image != nil
            else { return }
            
            
            DispatchQueue.main.async() {
                self.image = image
            }
        }.resume()
    }
    func dowloadFromServer(link: String, contentMode mode: UIView.ContentMode = .scaleAspectFill) {
        guard let url = URL(string: link) else { return }
        dowloadFromServer(url: url, contentMode: mode)
    }
}

//MARK: - 网络请求
func NetWork(url: String,params: NSMutableDictionary,fn: @escaping (_ obj: Any)-> Void){
    
    let token: String = UserDefaults.standard.value(forKey: "WeCloudIMCSdkToken") as! String
    var base_url: String = UserDefaults.standard.value(forKey: "WeCloudHttpUrl") as! String
    base_url.append(url)
    
    if token.count <= 0 {
        print("未登陆")
        return
    }
    
    var jsonData:Data? = nil
    
    do {
        jsonData = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    } catch {
    }
    
    let request: NSMutableURLRequest = NSMutableURLRequest(url: URL(string: base_url)!)
    request.httpMethod = "POST"
    request.timeoutInterval = 10
    
    request.addValue(token, forHTTPHeaderField: "token")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData
    
    let session = URLSession.shared
    
    session.dataTask(with:request as URLRequest) { data, response, error in
        guard error == nil else {
            print("网络出错:\(error!.localizedDescription)")
            return
        }
        
        guard data != nil else {
            print("数据为空：")
            return
        }
        
        do {
            let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
            print(jsonData)
            let data: NSDictionary = jsonData as! NSDictionary 
            
            if data != nil && data.object(forKey: "code") as! Int == 200{
                fn(data.object(forKey: "data") as Any)
            }
        } catch {
            print("解析出错")
        }
    }.resume()
}
